<template>
  <Splitpanes class="area">
    <!-- 左侧报告单元列表 -->
    <Pane :size="30">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input v-model="searchForm.groupSearchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getdictItemList" @keyup="keyupdictItemEnter" @search-click="getdictItemList()"></vxe-input>
          <vxe-select ref="refType" v-model="hrForm.interfaceId" placeholder="请选择接口" style="width:45%;">
            <vxe-option v-for="intf in interfaceTypeList" :key="intf.id" :label="intf.interfaceName" :value="intf.id"></vxe-option>
          </vxe-select>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="dictItemShowLoading" @click="getdictItemList"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="leftTable">
        <vxe-table ref="labdictItemTable" border class="mytable-scrollbar" height="700" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @current-change="grouprowClick" :data="dictItemList" :loading="dictItemShowLoading">
          <vxe-column type="seq" title="#" width="30"></vxe-column>
          <vxe-column field="itemNo" title="项目编号" width="150"></vxe-column>
          <vxe-column field="itemNa" title="项目名称"></vxe-column>
          <vxe-column field="rptGroup" title="报告单元"></vxe-column>
        </vxe-table>
        <vxe-pager align="left" min-height="32px" style="margin-top:10px;" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
      </div>
    </Pane>
    <!-- 中间对照信息 -->
    <Pane :size="36">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findItemDictList"></vxe-button>
        </template>
      </vxe-toolbar>

      <div class="leftTable">
        <vxe-table ref="dictItemVsItemdictTable" border class="mytable-scrollbar" height="750" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" :data="dictItemVsItemdictList" :loading="showLoading" @cell-dblclick="deletedictItemVsItemdictList" :edit-config="{ trigger: 'click', mode: 'cell' }" :column-config="{ resizable: true }">
          <!-- <vxe-column type="checkbox" width="30px" align="center"></vxe-column> -->
          <vxe-column type="seq" title="序号" width="50"></vxe-column>
          <vxe-column field="rptGroup" title="报告单元"></vxe-column>
          <vxe-column field="uploadItemNo" title="互认项目编码"></vxe-column>
          <vxe-column field="uploadItemNa" title="互认项目名称"></vxe-column>
          <vxe-column field="itemNo" title="申请项目编码"></vxe-column>
          <vxe-column field="itemNa" title="申请项目名称"></vxe-column>
        </vxe-table>
      </div>
    </Pane>
    <!-- 右侧信息 -->
    <Pane :size="34">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input v-model="searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getItemDictList" @keyup="keyupItemDictEnter" @search-click="getItemDictList()"></vxe-input>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getItemDictList"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addHrItem"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-upload" content="导入数据" @click="upload"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="rightTable">
        <vxe-table ref="itemDictTable" border show-header-overflow height="750" show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="itemDictRowClick" :data="itemDictList" :loading="showLoading" class="mytable-scrollbar">
          <vxe-column type="seq" title="#" width="30"></vxe-column>
          <vxe-column field="itemNo" title="互认项目代码" :edit-render="{ autofocus: '.vxe-input--inner' }">
          </vxe-column>
          <vxe-column field="itemNa" title="互认项目名称" :edit-render="{ autofocus: '.vxe-input--inner' }">
          </vxe-column>
          <vxe-column field="right" label="操作" width="80" align="center">
            <template #default="{ row, rowIndex }">
              <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click="itemEdit(row)"> </vxe-button>
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="itemDelete(row)"> </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </Pane>
  </Splitpanes>
  <!-- 添加或修改定时任务对话框 -->
  <vxe-modal class-name="addEditHrItemDialog" v-model="openHrItem" title="编辑互认项目" width="40vw" height="50vh" show-zoom resize>
    <el-form ref="formRef" :model="hrForm" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="申请项目编码" prop="itemNo">
            <el-input v-model="hrForm.itemNo" placeholder="请输入申请项目编码"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申请项目名称" prop="itemNa">
            <el-input v-model="hrForm.itemNa" placeholder="请输入申请项目名称"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialogFooter">
      <el-button type="primary" @click="submitHrForm">确 定</el-button>
      <el-button @click="cancelHrForm">取 消</el-button>
    </div>
  </vxe-modal>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import SelectWorkGroup from '@/views/lab_sys/lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import { IsEmpty } from '@/utils/common';
import VXETable from 'vxe-table';

let store = AppStore();
// 全局变量定义区 ==========
// 变量定义区
let { proxy }: any = getCurrentInstance();
let conWidth = ref(document.documentElement.clientWidth);
const itemDictList = reactive([]);
let selevctdictItemRow: any = reactive({
  id: ''
});

let searchGroupForm = reactive({
  rptGroup: ''
});

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let dictItemList = reactive([]);
let showLoading = ref(false); //刷新+表格加载
let dictItemShowLoading = ref(false);
let searchValue = ref('');
let searchValueVS = ref('');
const searchForm = reactive({
  orgId: store.userInfo.orgId,
  groupSearchValue: '',
  name: store.userInfo.orgName
});
let instrSetupList = reactive([]); //仪器列表
let channelList = reactive([]); //通道号列表
let dataIndex = ref(null); //数据索引
let addDialog = ref(false); //添加弹框展示状态
let loading = ref(false); //添加弹框展示状态
let rowData = ref({}); //当前行数据
let hrForm = reactive({});
let openHrItem = ref(false);
let interfaceTypeList = reactive([]);
let props = defineProps({
  systemId: String,
  moduleId: String,
  moduleSystemName: String
}) as any;

watch(
  () => props.systemId,
  (n, o) => {
    getdictItemList();
    findInterfaceList();
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.moduleId,
  (newval, oldvbal) => {
    getdictItemList();
  },
  {
    deep: true
  }
);

const dictItemVsItemdictList = reactive([]);

function findInterfaceList() {
  interfaceTypeList.length = 0;
  const url = '/api/sys/SysInterfaceCaUser/findInterfaceList';
  proxy.$http
    .get(url, { params: { systemId: props.systemId, moduleId: props.moduleId } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        interfaceTypeList.push(...res.data);
        hrForm.interfaceId = res.data[0].id;
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function addHrItem() {
  hrForm.id = '';
  hrForm.itemNo = '';
  hrForm.itemNa = '';
  openHrItem.value = true;
}

async function upload() {
  const { file } = await VXETable.readFile();
  uploadByUrl(file);
}
function uploadByUrl(file) {
  let url = '/lab/uploadItem/uploadUploadItem';
  const fd = new FormData();
  fd.append('file', file);
  proxy.$http
    .post(url, fd)
    .then((res: any) => {
      getItemDictList();
    })
    .catch((err) => {
      (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
    });
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getdictItemList();
}

function itemEdit(row) {
  Object.assign(hrForm, row);
  openHrItem.value = true;
}

function submitHrForm() {
  hrForm.type = 2;
  if (hrForm.id) {
    proxy.$http
      .post('/lab/uploadItem/editUploadItem', hrForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          openHrItem.value = false;
          VxeMessage('修改成功', VxeNotifyType.success);
          getItemDictList();
        } else {
          return;
        }
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  } else {
    proxy.$http
      .post('/lab/uploadItem/addUploadItem', hrForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          openHrItem.value = false;
          VxeMessage('添加成功', VxeNotifyType.success);
          getItemDictList();
        } else {
          return;
        }
      })
      .catch((err: any) => {
        VxeMessage('添加异常', VxeNotifyType.error);
      });
  }
}

async function itemDelete(row) {
  const type = await VXETable.modal.confirm('确定要删除当前数据？');
  if (type === 'confirm') {
    const data = {
      id: row.id
    };
    const url = '/lab/uploadItem/deleteUploadItem';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (res.status.code === 1) {
          getItemDictList();
          VxeMessage('删除成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

//关闭窗口
function closeAddDialog() {
  addDialog.value = false;
}

// 点击当前行// 行点击事件
function rptRowClick({ row }: any) {
  const $reportTable = proxy.$refs.labchannelTableRef;
  if ($reportTable) {
    $reportTable.setCurrentRow(row);
  }
  addDialog.value = false;
  findItemDictList();
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function getItemDictList() {
  findDictItemBydictItemId(selevctdictItemRow);
}

// 回车查询
function keyupdictItemEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getdictItemList();
  }
}

function keyupItemDictEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getItemDictList();
  }
}

// 获取申请项目
function getdictItemList() {
  dictItemList.length = 0;
  dictItemShowLoading.value = true;
  const url = '/lis/lab/item/findLabItemPageList1';
  let obj = {
    params: {
      seachValue: searchForm.groupSearchValue,
      orgId: searchForm.orgId,
      rptGroup: searchGroupForm.rptGroup,
      pageIndex: page.currentPage,
      pageSize: page.pageSize
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res && res.data && res.data.records.length > 0) {
        dictItemList.push(...res.data.records);
        page.totalResult = res.data.total;
        if (dictItemList.length > 0) {
          const kn = dictItemList.find((k) => k.id == selevctdictItemRow.id);
          if (isEmpty(kn)) {
            grouprowClick({ row: dictItemList[0] });
          } else {
            grouprowClick({ row: kn });
          }
        } else {
          selevctdictItemRow.id = '';
          dictItemVsItemdictList.length = 0;
        }
      } else {
        selevctdictItemRow.id = '';
        dictItemVsItemdictList.length = 0;
      }
      dictItemShowLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      dictItemShowLoading.value = false;
    });
}

// 获取报告项目列表
function findDictItemBydictItemId(row: any) {
  itemDictList.length = 0;
  showLoading.value = true;
  const url = '/lab/uploadItem/findUploadItem';
  let obj = {
    params: {
      type: 2,
      searchValue: searchValue.value,
      code: selevctdictItemRow.itemNo,
      interfaceId: hrForm.interfaceId,
      rptGroup: selevctdictItemRow.rptGroup
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        itemDictList.push(...res.data);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}

// 点击当前行// 行点击事件
function grouprowClick({ row }: any) {
  (proxy.$refs.labdictItemTable as any).setCurrentRow(row);
  selevctdictItemRow = row;
  proxy.$nextTick(() => {
    setTimeout(() => {
      (proxy.$refs.labdictItemTable as any).scrollToRow(row);
    }, 150);
  });
  findItemDictList();
  findDictItemBydictItemId(row);
}

// 获取中间的报告单元信息
function findItemDictList() {
  dictItemVsItemdictList.length = 0;
  const url = '/lab/uploadItem/findUploadItemVsItemByCode';
  const data = {
    params: {
      rptGroup: selevctdictItemRow.rptGroup,
      code: selevctdictItemRow.itemNo,
      type: 2,
      interfaceId: hrForm.interfaceId
    }
  };
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      dictItemVsItemdictList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//双击右侧列表
function itemDictRowClick({ row }: any) {
  if (isEmpty(selevctdictItemRow.id)) {
    VxeMessage('请选择申请项目', VxeNotifyType.error);
    return;
  }
  const url = '/lab/uploadItem/addUploadItemVsItem';
  let labdictItemVsItemDict = {
    itemNo: selevctdictItemRow.itemNo,
    itemNa: selevctdictItemRow.itemNa,
    uploadItemNo: row.itemNo,
    uploadItemNa: row.itemNa,
    rptGroup: selevctdictItemRow.rptGroup,
    type: 2,
    seq: dictItemVsItemdictList.length + 1,
    interfaceId: hrForm.interfaceId
  };
  proxy.$http
    .post(url, labdictItemVsItemDict)
    .then((res: any) => {
      findItemDictList();
      findDictItemBydictItemId(row);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 双击中间列表删除数据
function deletedictItemVsItemdictList({ row }: any) {
  const url = '/lab/uploadItem/deleteUploadItemVsItem';
  proxy.$http
    .post(url, {
      id: row.id
    })
    .then((res: any) => {
      findItemDictList();
      findDictItemBydictItemId(row);
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
</script>
<style lang="scss" scoped>
#applyVSReport {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: 100%;

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
  .dialogFooter {
    text-align: right;
  }
}
</style>
